package com.tianci.appstore.controller;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.RemoteException;

import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.app.CoocaaApplication.NetChangeReceiver.NetChangeReceiverListener;
import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.FansChannelUpgrade;
import com.coocaa.x.framework.utils.LiteHandlerThread;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.litedownloader.aidl.IDownloaderServiceListener;
import com.coocaa.x.service.litedownloader.data.DownloadError;
import com.coocaa.x.service.litedownloader.data.DownloadExtra;
import com.coocaa.x.service.litedownloader.data.DownloadTask;
import com.coocaa.x.service.litedownloader.data.ProcessInfo;
import com.coocaa.x.service.litepm.aidl.ILitePMInstallListener;
import com.coocaa.x.service.litepm.aidl.ILitePMUninstallListener;
import com.coocaa.x.service.litepm.data.AppInfo;
import com.coocaa.x.service.litepm.data.InstallParams;
import com.tianci.appstore.R;
import com.tianci.appstore.ui.SkinManager;
import com.tianci.appstore.ui.data.SkyListAppData;
import com.tianci.appstore.ui.widget.TipToast;
import com.tianci.appstore.utils.AsyncTask;
import com.tianci.appstore.utils.ImageUtils;
import com.tianci.appstore.utils.SkyConstants;
import com.tianci.appstore.utils.SkyNetImageCache;
import com.tianci.appstore.utils.SkyNetImageCache.ImageLoadListener;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

public abstract class AppStoreBaseController {
    public interface UpdateDownloadCountHandler {
        void updateDownloadCount(int count);
    }

    public static Context mContext = CoocaaApplication.getContext();
    public static boolean NETSTATUS = true;

    private static ReentrantLock lock = new ReentrantLock();
    protected List<SkyListAppData> mFailedList = new ArrayList<SkyListAppData>();
    protected SkyListAppData mTempAppData = null;
    private static List<UpdateDownloadCountHandler> countHandlers = new ArrayList<UpdateDownloadCountHandler>();

    private static NetChangeReceiverListener netChangeListener = new NetChangeReceiverListener() {
        @Override
        public void onNetStateChanged(boolean bConnected) {
            NETSTATUS = bConnected;
            if (!bConnected) {
                runOnThread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        try {
                            XServiceManager.getDownloaderService().stopAll();
                        } catch (RemoteException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
    };

    private static IDownloaderServiceListener.Stub downloaderStub = new IDownloaderServiceListener.Stub() {
        @Override
        public void onReady(DownloadTask task) throws RemoteException {
            // TODO Auto-generated method stub
            updateDownloadCount(null);
        }

        @Override
        public void onPrepare(DownloadTask task) throws RemoteException {
            // TODO Auto-generated method stub
        }

        @Override
        public void onStart(final DownloadTask task) throws RemoteException {
            // TODO Auto-generated method stub
            updateDownloadCount(null);
            DownloadExtra extra = DownloadExtra.parseJObject(task.extra, DownloadExtra.class);


            //ToDo
            //这个下载网络图片导致 “xx开始下载” 的toast显示缓慢
            //需要优化
            SkyNetImageCache.getSkyNetImageCache().downloadUrl(extra.pkgname, extra.iconUrl,
                    new ImageLoadListener() {
                        @Override
                        public void loadFinished(String url, final Bitmap result) {
                            // TODO Auto-generated method stub
                            final String str = String.format(
                                    mContext.getResources().getString(R.string.tips_startdownload),
                                    task.title);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    // TODO Auto-generated method stub
                                    Bitmap bm;
                                    try {
                                        bm = ImageUtils.getRoundedCornerBitmap(result, 25);
                                    } catch (Exception e) {
                                        bm = result;
                                    }
                                    TipToast.getInstance(mContext).showToast(bm, str);
                                }
                            });
                        }
                    }, SkyConstants.iconWidth, SkyConstants.iconWidth);
        }

        @Override
        public void onStop(DownloadTask task) throws RemoteException {
            // TODO Auto-generated method stub
            updateDownloadCount(null);
        }

        @Override
        public void onProcessInfo(DownloadTask task, ProcessInfo info) throws RemoteException {
            // TODO Auto-generated method stub

        }

        @Override
        public void onFinish(DownloadTask task) throws RemoteException {
            // TODO Auto-generated method stub
            updateDownloadCount(null);
            String title = task.title;
            LogUtils.d("fans", "onFinish name:" + title);
            if(title != null && !title.equals(""))
            FansChannelUpgrade.insertDownloadData(task.title, System.currentTimeMillis() / 1000);
        }

        @Override
        public void onError(DownloadTask task, final DownloadError error) throws RemoteException {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    switch (error.errcode) {
                        case DownloadError.ERRCODE_NO_DISK_SPACE: {
                            TipToast.getInstance(mContext).showToast(
                                    SkinManager.getResDrawable(R.drawable.toast_icon_tip),
                                    mContext.getResources().getString(R.string.no_free_download_size));
                            break;
                        }
                        case DownloadError.ERRCODE_MD5_CHECK_ERROR: {
                            TipToast.getInstance(mContext).showToast(
                                    SkinManager.getResDrawable(R.drawable.toast_icon_tip), "文件校验失败,请重新下载");
                            break;
                        }
                        default:
                            break;
                    }
                }
            });
            updateDownloadCount(null);
        }

        @Override
        public void onDelete(DownloadTask task) throws RemoteException {
            // TODO Auto-generated method stub
            updateDownloadCount(null);
        }
    };

    private static ILitePMInstallListener.Stub installStub = new ILitePMInstallListener.Stub() {
        @Deprecated
        private void showInstallEndToast(String apkfile, final AppInfo appInfo, final int success,
                                         final String extra) {
            // 这个根据状态进行的toast弹框提示，之后统一整合到LiteToastDaemon中
            if (success == 0) {
                Bitmap bitmap = null;
                try {
                    PackageInfo info = mContext.getPackageManager().getPackageInfo(appInfo.pkgName, 0);
                    bitmap = ((BitmapDrawable) info.applicationInfo.loadIcon(mContext
                            .getPackageManager())).getBitmap();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                final Bitmap _bitmap = bitmap;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        Bitmap bitmap = _bitmap;
                        String tipStr = mContext.getResources()
                                .getString(R.string.tips_installdone);
                        // 弱提示 应用安装完成
                        if (bitmap != null) {
                            try {
                                bitmap = ImageUtils.getRoundedCornerBitmap(bitmap, 25);
                            } catch (Exception e) {
                            }
                            TipToast.getInstance(mContext).showToast(bitmap, tipStr);
                        } else
                            TipToast.getInstance(mContext).showToast(
                                    SkinManager.getResDrawable(R.drawable.toast_icon_tip), tipStr);
                    }
                });
//                try {
//                    XServiceManager.getLiteCCConnectorService().installAppPoints(appInfo.pkgName);
//                } catch (RemoteException e) {
//                    e.printStackTrace();
//                }
            }
            if (CoocaaApplication.isRoot()) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (success != 0) {
                            if (extra != null) {
                                LogUtils.d("install", "install error extra:" + extra);
                                if (extra.contains("INSTALL_FAILED_INSUFFICIENT_STORAGE")) {
                                    TipToast.getInstance(mContext).showToast(
                                            SkinManager.getResDrawable(R.drawable.toast_icon_tip),
                                            mContext.getResources().getString(
                                                    R.string.no_free_install_size));
                                } else if (extra.contains("nosdcard")) {
                                    TipToast.getInstance(mContext)
                                            .showToast(
                                                    SkinManager
                                                            .getResDrawable(R.drawable.toast_icon_tip),
                                                    "安装失败，请插入SDcard!");
                                } else if (extra.contains("systemuid")) {
                                    TipToast.getInstance(mContext)
                                            .showToast(
                                                    SkinManager
                                                            .getResDrawable(R.drawable.toast_icon_tip),
                                                    "安装失败，请设置安装应用到本机!");
                                } else if (extra.contains("INSTALL_FAILED_INVALID_APK")) {
                                    TipToast.getInstance(mContext)
                                            .showToast(
                                                    SkinManager
                                                            .getResDrawable(R.drawable.toast_icon_tip),
                                                    mContext.getResources().getString(
                                                            R.string.invalid_apk));
                                } else {
                                    TipToast.getInstance(mContext).showToast(
                                            SkinManager.getResDrawable(R.drawable.toast_icon_tip),
                                            mContext.getResources().getString(
                                                    R.string.install_failed));
                                }
                            }
                        }
                    }
                });
            }
        }

        @Override
        public void onInstallEnd(final String apkfile, final AppInfo appInfo, final int success,
                                 final String extra, final InstallParams params) throws RemoteException {
            runOnThread(new Runnable() {
                @Override
                public void run() {
                    showInstallEndToast(apkfile, appInfo, success, extra);
                }
            });
        }

        @Override
        public void onInstallStart(String arg0, AppInfo appInfo, final InstallParams params) throws RemoteException {

        }

    };

    private static ILitePMUninstallListener.Stub uninstallStub = new ILitePMUninstallListener.Stub() {
        @Override
        public void onUninstallEnd(AppInfo appInfo, final int success, String extra) throws RemoteException {
            // TODO Auto-generated method stub
            final String appName = appInfo.appName;
            LogUtils.d("un", " uninstallStub  appName:" + appName + " success:" + success);
            if (appName != null && !appName.equals("")) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (success == 0) {
                            TipToast.getInstance(mContext).showToast(
                                    SkinManager.getResDrawable(R.drawable.toast_icon_ok),
                                    appName + "卸载成功");
                        } else
                            TipToast.getInstance(mContext).showToast(
                                    SkinManager.getResDrawable(R.drawable.toast_icon_tip),
                                    appName + "卸载失败");
                    }
                });
            }
        }

        @Override
        public void onUninstallStart(AppInfo appInfo) throws RemoteException {
            // TODO Auto-generated method stub

        }
    };

    public static synchronized void setContext(Context context) {
        mContext = context;
        if (!Android.isNetConnected(context)) {
            NETSTATUS = false;
        } else {
            NETSTATUS = true;
        }
        runOnThread(new Runnable() {
            @Override
            public void run() {
                CoocaaApplication.addNetChangedListener(netChangeListener);

                try {
                    XServiceManager.getDownloaderService().setListener(downloaderStub);
                } catch (RemoteException e1) {
                    e1.printStackTrace();
                }
                try {
                    XServiceManager.getLitePMService().addInstallListener(installStub);
                } catch (RemoteException e1) {
                    e1.printStackTrace();
                }
                try {
                    XServiceManager.getLitePMService().addUninstallListener(uninstallStub);
                } catch (RemoteException e1) {
                    e1.printStackTrace();
                }

                try {
                    updateDownloadCount(null);

                    int need2install = 0;
                    int tips_need2restartdownload = 0;
                    List<DownloadTask> list = XServiceManager.getDownloaderService().getTaskList();
                    for (DownloadTask task : list) {
                        switch (task.info.state) {
                            case FINISH: {
                                need2install++;
                                break;
                            }
                            case PROCESSING: {
                                tips_need2restartdownload++;
                                break;
                            }
                            default:
                                break;
                        }
                    }
                    if (need2install > 0) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                // TODO Auto-generated method stub
                                TipToast.getInstance(mContext).showToast(
                                        SkinManager.getResDrawable(R.drawable.toast_icon_tip),
                                        mContext.getResources().getString(
                                                R.string.tips_need2install));// 弱提示
                                // 有应用下载完成，需要安装
                            }
                        });
                    }
                    if (tips_need2restartdownload > 0) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                // TODO Auto-generated method stub
                                TipToast.getInstance(mContext).showToast(
                                        SkinManager.getResDrawable(R.drawable.toast_icon_tip),
                                        mContext.getResources().getString(
                                                R.string.tips_need2restartdownload));// 弱提示
                                // 中断下载已恢复
                            }
                        });
                    }
                } catch (RemoteException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }

    public static void addUpdateDownloadCountHandler(final UpdateDownloadCountHandler handler) {
        runOnThread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                lock.lock();
                if (!countHandlers.contains(handler))
                    countHandlers.add(handler);
                lock.unlock();
                updateDownloadCount(handler);
            }
        });
    }

    public static void removeUpdateDownloadCountHandler(final UpdateDownloadCountHandler handler) {
        runOnThread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                lock.lock();
                countHandlers.remove(handler);
                lock.unlock();
            }
        });
    }

    private static void updateDownloadCount(final UpdateDownloadCountHandler handler) {
        runOnThread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    List<DownloadTask> list = XServiceManager.getDownloaderService().getTaskList();
                    int count = 0;
                    for (DownloadTask task : list) {
                        switch (task.info.state) {
                            case PROCESSING:
                            case READY:
                                count++;
                            default:
                                break;
                        }
                    }
                    final int _count = count;
                    lock.lock();
                    if (handler == null) {
                        for (final UpdateDownloadCountHandler handler : countHandlers) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    // TODO Auto-generated method stub
                                    handler.updateDownloadCount(_count);
                                }
                            });
                        }
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                // TODO Auto-generated method stub
                                handler.updateDownloadCount(_count);
                            }
                        });
                    }
                    lock.unlock();
                } catch (RemoteException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }

    protected static void runOnUiThread(Runnable runnable) {
        LiteHandlerThread.postOnUiThread(runnable);
    }

    protected static void runOnThread(Runnable runnable) {
        AsyncTask.runOnThread(runnable);
    }

    protected final String LOG_PAGENAME = getClass().getSimpleName();

    public String getModuleName() {
        return LOG_PAGENAME;
    }

    protected synchronized void sendBtnClickLOG(String action, int appid, String appName) {
    }

    protected synchronized void sendBtnClickLOG(String action) {
        sendBtnClickLOG(action, -1, "");
    }

    public AppStoreBaseController() {
    }

    public String getString(int id) {
        return mContext.getResources().getString(id);
    }

    public abstract void destroy();
}
